<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Api } from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user.js'

const userStore = useUserStore()
const token = ref(userStore.token)
const users = ref([])
const loading = ref(false)
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页显示条数
const totalUsers = ref(0) // 用户总数

// 控制添加用户弹窗的显示
const addUserDialogVisible = ref(false)
// 控制编辑用户弹窗的显示
const editUserDialogVisible = ref(false)

// 添加用户表单数据
const addUserForm = reactive({
  username: '',
  password: '',
  phone: '',
  role: 'none', // 添加角色字段，默认为none
  is_admin: false,
  is_counselor: false,
  is_assistantn: false,
})

// 编辑用户表单数据
const editUserForm = reactive({
  id: '',
  username: '',
  name: '',
  phone: '',
  email: '',
  password: '', // 添加密码字段
  is_admin: false,
  is_counselor: false,
  is_assistantn: false,
})

// 获取用户列表（支持分页）
const fetchUsers = async () => {
  try {
    loading.value = true
    const response = await Api.getAllUsers({
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    users.value = response.data.data.users
    totalUsers.value = response.data.data.total
    console.log('用户列表已更新:', users.value)
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 分页改变时触发
const handlePageChange = (page) => {
  currentPage.value = page
  fetchUsers()
}

// 每页条数改变时触发
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchUsers()
}

// 判断是否为 Excel 文件
const beforeUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  return true
}

const handleSuccess = (res) => {
  try {
    if (res.status === 200) {
      ElMessage.success('导入成功')
      fetchUsers() // 调用刷新用户列表的方法
    } else {
      ElMessage.error(res.message || '导入失败')
    }
  } catch (error) {
    console.error('处理导入成功响应时出错:', error)
    ElMessage.error('导入成功，但处理响应时出错')
  }
}

const handleError = (err) => {
  ElMessage.error('导入失败: ' + JSON.parse(err.message).message)
}

// 删除用户
const deleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(`确认删除用户 ${user.username} 吗？`, '提示', {
      type: 'warning',
    })
    await Api.deleteUser({ id: user.id })
    ElMessage.success('删除成功')
    fetchUsers() // 刷新用户列表
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除用户失败，请稍后再试')
  }
}

// 编辑用户
const editUser = (user) => {
  editUserForm.id = user.id
  editUserForm.username = user.username
  editUserForm.name = user.name || ''
  editUserForm.phone = user.phone || ''
  editUserForm.email = user.email || ''
  editUserForm.password = '' // 重置密码字段
  editUserForm.is_admin = user.is_admin || false
  editUserForm.is_counselor = user.is_counselor || false
  editUserForm.is_assistantn = user.is_assistantn || false
  editUserDialogVisible.value = true
}

// 提交编辑用户表单
const onEditUserSubmit = async () => {
  try {
    // 创建一个新对象，只包含需要提交的字段
    const submitData = {
      id: editUserForm.id,
      username: editUserForm.username,
      name: editUserForm.name,
      phone: editUserForm.phone,
      email: editUserForm.email,
      is_admin: editUserForm.is_admin,
      is_counselor: editUserForm.is_counselor,
      is_assistantn: editUserForm.is_assistantn
    }

    // 如果密码不为空，则添加到提交数据中
    if (editUserForm.password) {
      submitData.password = editUserForm.password
    }

    await Api.updateUser(submitData)
    ElMessage.success('用户信息更新成功')
    editUserDialogVisible.value = false
    fetchUsers() // 刷新用户列表
  } catch (error) {
    console.error('更新用户失败:', error)
    ElMessage.error('更新用户失败，请稍后再试')
  }
}

// 监听角色变化并更新对应的权限字段
const handleRoleChange = (role) => {
  // 先重置所有权限
  addUserForm.is_admin = false
  addUserForm.is_counselor = false
  addUserForm.is_assistantn = false

  // 根据选择的角色设置对应的权限
  switch (role) {
    case 'admin':
      addUserForm.is_admin = true
      break
    case 'counselor':
      addUserForm.is_counselor = true
      break
    case 'assistant':
      addUserForm.is_assistantn = true
      break
    default:
      // 'none' 的情况，所有权限都为 false
      break
  }
}

// 重置添加用户表单
const resetAddUserForm = () => {
  addUserForm.username = ''
  addUserForm.password = ''
  addUserForm.phone = ''
  addUserForm.role = 'none'
  addUserForm.is_admin = false
  addUserForm.is_counselor = false
  addUserForm.is_assistantn = false
}

// 打开添加用户弹窗
const openAddUserDialog = () => {
  resetAddUserForm() // 必须最先调用，确保所有字段为空
  addUserDialogVisible.value = true
}

// 提交添加用户表单
const onAddUserSubmit = async () => {
  try {
    // 确保在提交前更新一次权限设置
    handleRoleChange(addUserForm.role)

    console.log('提交的用户数据:', addUserForm) // 调试输出

    // 创建一个新对象，只包含需要提交的字段
    const submitData = {
      username: addUserForm.username,
      password: addUserForm.password,
      phone: addUserForm.phone,
      is_admin: addUserForm.is_admin,
      is_counselor: addUserForm.is_counselor,
      is_assistantn: addUserForm.is_assistantn
    }

    await Api.register(submitData)
    ElMessage.success('用户添加成功')
    addUserDialogVisible.value = false // 关闭弹窗
    fetchUsers() // 刷新用户列表

    // 重置表单
    addUserForm.username = ''
    addUserForm.password = ''
    addUserForm.phone = ''
    addUserForm.role = 'none'
    addUserForm.is_admin = false
    addUserForm.is_counselor = false
    addUserForm.is_assistantn = false
  } catch (error) {
    console.error('添加用户失败:', error)
    if (error.response) {
      const msg = error.response.data && error.response.data.message;
      // If the message includes '用户名已存在', do nothing (skip ElMessage)
      if (msg && msg.includes('用户名已存在')) {
         // Do nothing, effectively removing the message for this specific case
      } else if (msg) {
         // Show other specific messages from backend
         ElMessage.error(msg);
      }
      // Network error and other cases without a specific message are handled by the outer else or implicitly skipped
    } else {
      // Handle network error
      ElMessage.error('网络错误，请检查您的网络连接');
    }
  }
}

onMounted(() => {
  fetchUsers()
})
</script>

<template>
  <div class="user-management">
    <h1>用户信息管理</h1>
    <div style="display: flex; align-items: center; margin-bottom: 20px;">
    <!-- 批量导入 -->
    <el-upload
      :headers="{ Authorization: 'Bearer ' + token }"
      action="http://localhost:4000/api/uploadXlsxUsers"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      accept=".xlsx"
      style="margin-right: 20px;"
    >
      <el-button type="primary">批量导入用户信息</el-button>
    </el-upload>

    <!-- 添加用户按钮 -->
    <el-button type="primary" @click="openAddUserDialog">添加用户</el-button>
  </div>


    <!-- 用户列表 -->
    <el-table :data="users" v-loading="loading" style="width: 100%">
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="手机号码" />
      <el-table-column prop="is_admin" label="管理员" />
      <el-table-column prop="is_counselor" label="咨询师" />
      <el-table-column prop="is_assistantn" label="辅导员" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalUsers"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      style="margin-top: 20px;"
    />

    <!-- 添加用户弹窗 -->
    <el-dialog
      v-model="addUserDialogVisible"
      title="添加用户"
      :close-on-click-modal="false"
      @closed="resetAddUserForm"
    >
      <el-form :model="addUserForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addUserForm.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="addUserForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="addUserForm.role" @change="handleRoleChange">
            <el-radio label="admin">管理员</el-radio>
            <el-radio label="counselor">咨询师</el-radio>
            <el-radio label="assistant">辅导员</el-radio>
            <el-radio label="none">无</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onAddUserSubmit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="editUserDialogVisible" title="编辑用户信息" width="500px">
      <el-form :model="editUserForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editUserForm.password" placeholder="不修改请留空" type="password" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editUserForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="editUserForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editUserForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox v-model="editUserForm.is_admin">管理员</el-checkbox>
          <el-checkbox v-model="editUserForm.is_counselor">咨询师</el-checkbox>
          <el-checkbox v-model="editUserForm.is_assistantn">辅导员</el-checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editUserDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onEditUserSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  padding: 20px;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.operation-buttons .el-button {
  margin: 0;
}

/* 添加新的样式 */
:deep(.el-checkbox) {
  margin-right: 20px;
}

:deep(.el-form-item__content) {
  justify-content: flex-start;
}
</style>
